package com.mmall.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.JedisClient;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.UserService;
import com.mmall.util.JsonUtils;
import com.mmall.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.*;

import static java.lang.System.out;

@Service("UserService")
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JedisClient jedisClient;

    @Override
    public ServerResponse login(String stuId, String password) {
        if(userMapper.selectUserByStuId(stuId)==null){
            return ServerResponse.createByErrorCodeMessage(Const.STU_ID_IS_NOT_EXIST,"学号不存在");
        }
        User user = userMapper.selectLogin(stuId,password);
        if(user != null){
//            Map<String,User> userMap = new HashMap<>();
            String loginToken = MD5Util.MD5EncodeUtf8(stuId);
            user.setPassword(null);//置空密码
//            userMap.put(token,user);
            //将用户信息存入redis
            jedisClient.set(Const.PREFIX_REDIS_USER+"_:"+loginToken,JsonUtils.objectToJson(user));
            jedisClient.expire(Const.PREFIX_REDIS_USER+"_:"+loginToken,604800);//设置缓存时间为一周
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Const.TOKEN_LOGIN,loginToken);
            jsonObject.put(Const.USER_NICK_NAME,user.getNickName());
            jsonObject.put(Const.USER_FACE,user.getUserface());
            return ServerResponse.cerateBySuccess("登录成功",jsonObject);
        }
        return ServerResponse.createByErrorCodeMessage(Const.LOGIN_FAIL,"用户名或密码错误");
    }

    @Override
    public ServerResponse updateInfo(User user,String loginToken) {
        User user1 = userMapper.selectUserByEmail(user.getEmail());
        if(user1!=null && user.getId()!=null && !user.getId().equals(user1.getId())){//排除当前用户
            return ServerResponse.createByErrorMessage("该邮箱已被绑定");
        }
        if(userMapper.updateByPrimaryKeySelective(user)>0){
            User newUser = userMapper.selectUserByStuId(user.getStuId());
            newUser.setPassword(null);
            jedisClient.set(Const.PREFIX_REDIS_USER+"_:"+loginToken,JsonUtils.objectToJson(newUser));//更新缓存内容
            return ServerResponse.cerateBySuccess("个人信息更新成功",newUser);
        }
        return ServerResponse.createByErrorMessage("个人信息更新失败");
    }

    @Override
    public ServerResponse updatePassword(String stuId,String oldPwd, String newPwd) {
        String md5OldPwd = MD5Util.MD5EncodeUtf8(oldPwd);
        String md5NewPwd = MD5Util.MD5EncodeUtf8(newPwd);
        if(userMapper.selectLogin(stuId,md5OldPwd)==null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        if( userMapper.updatePwd(stuId,md5NewPwd)>0){
            return ServerResponse.cerateBySuccessMessage("密码修改成功");
        }
        return ServerResponse.createByErrorMessage("密码修改失败");
    }

    public ServerResponse resetPwd(String email, String password){
        if(userMapper.resetPwd(email,password)>0){
            return  ServerResponse.cerateBySuccessMessage("密码重置成功");
        }
        return ServerResponse.createByErrorMessage("密码重置失败");
    }

    public ServerResponse checkEmail(String email){
        if (userMapper.selectUserByEmail(email)!=null){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.cerateByError();
    }

    /**
     * 用户注销
     * @param loginToken
     * @return
     */
    public ServerResponse loginOut(String loginToken){
        try {
            jedisClient.del(Const.PREFIX_REDIS_USER+"_:"+loginToken);
            return ServerResponse.cerateBySuccessMessage("注销成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("注销账号错误");
        }

    }

    /**
     * 验证用户是否登录
     * @param loginToken
     * @return
     */
    public ServerResponse userIsLogin(String loginToken){
        if(loginToken==null){
            return ServerResponse.createByErrorMessage("还未登录");
        }
        String userString =jedisClient.get(Const.PREFIX_REDIS_USER+"_:"+loginToken);

        if(userString==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        Object userObject = JsonUtils.stringToJsonObject(userString);
        User user = JsonUtils.jsonToPojo(userObject.toString(),User.class);
        return ServerResponse.cerateBySuccess(user);
    }


    public ServerResponse register(String stuId,String password,String email){

        if(userMapper.selectUserByStuId(stuId)!=null){
            return ServerResponse.createByErrorMessage("学号已被注册");
        }
        if(userMapper.selectUserByEmail(email)!=null){
            return ServerResponse.createByErrorMessage("邮箱已存在");
        }
        User user = new User();
        user.setPassword(MD5Util.MD5EncodeUtf8(password));
        Random random = new Random();
        user.setUserface(String.valueOf(random.nextInt(20)%(21))+".jpg");  //给用户一个随机头像
        user.setRole(0);
        user.setStuId(stuId);
        user.setNickName(stuId);
        user.setEmail(email);
        user.setCreateTime(new Date());
        if(userMapper.insert(user)>0){
            return ServerResponse.cerateBySuccessMessage("注册成功");
        }
        return ServerResponse.createByErrorMessage("注册失败！");

    }


}
